import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Table, Button, Form, Input, Badge, Modal } from 'antd';
import { useNavigate } from 'react-router-dom';
import './table.css';

const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{ margin: 0 }}
          rules={[
            {
              required: true,
              message: `Please Input ${title}!`,
            },
          ]}
        >
          <Input />
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

const ModelManage = () => {
  const [data, setData] = useState([]);
  const [editingKey, setEditingKey] = useState('');
  const [visible, setVisible] = useState(false);
  const [imageSrc, setImageSrc] = useState('');
  const navigate = useNavigate();
  const [form] = Form.useForm();

  useEffect(() => {
    const fetchData = async () => {
      try {
        const res = await axios.get('http://39.106.250.42:5172/get_model');
        const data = res.data;
        if (Array.isArray(data)) {
          setData(data.map(item => ({
            key: item.model_id,
            modelId: item.model_id,
            name: item.name,
            location: item.location,
            type: item.type,
            attribute: item.attribute,
            state: item.state,
            json: item.json,
          })));
        } else {
          console.error('Data is not an array:', data);
        }
      } catch (err) {
        console.error(err);
      }
    };

    fetchData();
  }, []);

  const isEditing = (record) => record.key === editingKey;

  const edit = (record) => {
    form.setFieldsValue({
      name: '',
      state: '',
      type: '',
      ...record,
    });
    setEditingKey(record.key);
  };

  const cancel = () => {
    setEditingKey('');
  };

  const save = async (key) => {
    try {
      const row = await form.validateFields();
      const newData = [...data];
      const index = newData.findIndex((item) => key === item.key);

      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row });
        setData(newData);
        setEditingKey('');

        // 使用 axios.post 实时更新数据库中的数据
        await axios({
          method: "post",
          url: "http://39.106.250.42:5172/change_model",
          data: { ...item, ...row }
        }).then(res => {
          console.log(res);
        });
      } else {
        newData.push(row);
        setData(newData);
        setEditingKey('');
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };

  const handleUploadClick = (record) => {
    navigate('/manage', { state: { selectedKey: 'uploadPage', ...record } });
  };

  const handleImageClick = (src) => {
    setImageSrc(src);
    setVisible(true);
  };

  const stateMap = {
    uploading: '上传中',
    validate: '检验中',
    compress: '压缩中',
    evaluate: '验证中',
    ready: '就绪',
  };

  const columns = [
    {
      title: '模型ID',
      dataIndex: 'modelId',
      editable: false,
    },
    {
      title: '名称',
      dataIndex: 'name',
      editable: true,
    },
    {
      title: '位置',
      dataIndex: 'location',
      editable: true,
    },
    {
      title: '类型',
      dataIndex: 'type',
      editable: true,
    },
    {
      title: '模型描述',
      dataIndex: 'attribute',
      editable: true,
    },
    {
      title: '状态',
      dataIndex: 'state',
      editable: true,
      render: (text) => (
        <Badge
          status={text === 'ready' ? 'success' : 'processing'}
          text={stateMap[text]}
        />
      ),
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Button onClick={() => save(record.key)} style={{ marginRight: 8 }} >
              保存
            </Button>
            <Button onClick={cancel}>取消</Button>
          </span>
        ) : (
          <span>
            <Button onClick={() => edit(record)} style={{ marginRight: 8 }} ghost>
              编辑
            </Button>
            <Button onClick={() => handleUploadClick(record)} ghost>
              重传
            </Button>
            <Button ghost>
              上星
            </Button>
          </span>
        );
      },
    },
  ];

  const expandedRowRender = (record) => {
    const columns = [
      { title: '数据图表', dataIndex: ['evaluate', 'test_image'], key: 'test_image', render: (text) => text ? <Button onClick={() => handleImageClick(`http://39.106.250.42:5172/${text}`)}>View Image</Button> : 'No Image' },
      { title: '准确度', dataIndex: ['evaluate', 'acc_value'], key: 'acc_value' },
      { title: 'CPU占用', dataIndex: ['evaluate', 'cpu_occupancy'], key: 'cpu_occupancy' },
      { title: 'GPU占用', dataIndex: ['evaluate', 'gpu_occupancy'], key: 'gpu_occupancy' },
      { title: '内存占用', dataIndex: ['evaluate', 'memory_occupancy'], key: 'memory_occupancy' },
      { title: '压缩算法ID', dataIndex: ['compress', 'compress_algorithm_id'], key: 'compress_algorithm_id' },
      { title: '压缩前准确度', dataIndex: ['compress', 'pre-compression_acc'], key: 'pre_compression_acc' },
      { title: '压缩后准确度', dataIndex: ['compress', 'compressed_acc'], key: 'compressed_acc' },
      { title: '压缩前体积', dataIndex: ['compress', 'pre-compression_size'], key: 'pre_compression_size' },
      { title: '压缩后体积', dataIndex: ['compress', 'compressed_size'], key: 'compressed_size' },
      { title: '压缩率', dataIndex: ['compress', 'compression_ratio'], key: 'compression_ratio' },
      { title: '输入大小', dataIndex: ['format', 'input_size'], key: 'input_size' },
      { title: '原始格式', dataIndex: ['format', 'raw'], key: 'raw' },
      { title: '最终格式', dataIndex: ['format', 'final'], key: 'final' }
    ];

    return <Table columns={columns} dataSource={[record.json]} pagination={false} rowKey="test_image" />;
  };

  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });

  return (
    <div style={{ padding: '10px', minHeight: '100%', backgroundColor: 'transparent' }} className='model-manage-table'>
      <Form form={form} component={false}>
        <Table
          components={{
            body: {
              cell: EditableCell,
            },
          }}
          rowHoverable='False'
          dataSource={data}
          columns={mergedColumns}
          rowClassName="editable-row"
          pagination={{ pageSize: 10 }}
          rowKey="key"
          expandable={{ expandedRowRender }}
          scroll={{ x: 'max-content' }}
          style={{maxWidth:'100%'}}
        />
      </Form>
      <Modal visible={visible} footer={null} onCancel={() => setVisible(false)} style={{backgroundColor:'rgba(16, 58, 91, 0.85)', borderRadius:'0', border:'1px solid rgba(126, 156, 179, 0.8)'}}>
        <img alt="Test" style={{ width: '100%' }} src={imageSrc} />
      </Modal>
    </div>
  );
};

export default ModelManage;
